<?php
/**
 * 疯狂工厂  app 模块
 * 
 * @version $Id$
 */

class Module_factory
{
	/**
	 * 构造函数
	 */
	function __construct() {
		
	}
	
	/**
	 * 首页
	 */
	function index() {
		$uin = sessionInfo('uin');
		
		loadLib('App_factory');
		
		$info = App_factory::getInfo($uin);
		
		// 判断用户是否已经开通游戏
		if(empty($info)) {
			return $this->guide();
		}
		
		$info = App_factory::updateState($uin , $info , true);
		
		$smarty = loadSmarty();
		
		$smarty->assign('info' , $info);
		
		return $smarty->fetch('app/factory/index.tpl.php');
	}
	

	/**
	 * 引导开通工厂
	 */
	function guide() {
		$uin = sessionInfo('uin');
		
		// 判断用户是否已注册游戏，如果已注册，则定位到游戏首页
		
		$step = isset($_GET['step']) ? intval($_GET['step']) : 1;
		
		
		// 最后一步
		if($step == 4 && isset($_POST['open'])) {
			$time_now = time();
			
			loadLib('App_factory');
			$info = App_factory::getInfo($uin);
			if(!empty($info)) {
				header('Location: ' . SITEURL . '/app.php?m=factory&sid=' . sessionInfo('skey'));
				return;
			}
			
			// 开通，初始化
			$code = App_factory::initInfo($uin);
			if($code !== 0) {
				return View::error('系统繁忙，请稍后再试' , $code);
			}
			
			// 初始化钱
			loadLib('Currency');
			Currency::update('app_factory' , $uin , 10000);
			
			// 发feed
			loadLib('Feed');
			Feed::addContent($uin , '开始玩游戏疯狂工厂，大家一起来开厂赚钱吧' , 'normal' , array(
				array('name' => '进入游戏' , 'url' => SITEURL . '/app.php?m=factory')
			));
			
			header('Location: ' . SITEURL . '/app.php?m=factory&sid=' . sessionInfo('skey'));
			return;
		}
		
		$smarty = loadSmarty();
		
		$smarty->assign('step' , $step);
		if($step == 2) {
			$option = isset($_GET['option']) ? intval($_GET['option']) : 2;
			$smarty->assign('option' , $option);
		}
		
		return $smarty->fetch('app/factory/guide.tpl.php');
	}
	
	/**
	 * 老板办公室
	 */
	function office_boss() {
		$uin = sessionInfo('uin');
		$time_now = isset($_SERVER['REQUEST_TIME']) ? $_SERVER['REQUEST_TIME'] : time();

		$smarty = loadSmarty();
		loadLib('App_factory');
		
		$info = App_factory::updateState($uin , null , true);

		// 随机事件
		if($event_page = $this->_event_guide('office_boss' , $info)) {
			return $event_page;
		}
		
				
		$dairy_earn = App_factory::getLevelInfo($info['lines'] , 'daily_earn');
		
		loadLib('Currency');
		$currency = Currency::get('app_factory' , $uin);
		
		$smarty->assign('info' , $info);
		$smarty->assign('dairy_earn' , $dairy_earn);
		$smarty->assign('currency' , $currency);
		
		if($info['lines_info']['state'] == 1) {
			// 正在生产状态 
			$diff_time = $info['lines_timer'] - $time_now;
			$diff_time_correct = $diff_time + (16 * 3600);		// 因为我们时区是8
			$diff_time_array = explode(':' , date('H:i:s' , $diff_time_correct));
			$smarty->assign('diff_time' , $diff_time_array);
		} else if($info['lines_info']['state'] == 2) {
			// 生产结束可以收钱状态
		}
		
		return $smarty->fetch('app/factory/office_boss.tpl.php');
	}
	
	/**
	 * 秘书办公室
	 */
	function office_secretary() {
		$uin = sessionInfo('uin');
		$time_now = isset($_SERVER['REQUEST_TIME']) ? $_SERVER['REQUEST_TIME'] : time();

		$smarty = loadSmarty();
		loadLib('App_factory');
		
		$info = App_factory::updateState($uin , null , true);

		// 随机事件
		if($event_page = $this->_event_guide('office_secretary' , $info)) {
			return $event_page;
		}

		
		// 计算还剩余的时间
		if(count($info['secretary']) > 0) {
			$list = App_factory::getFriendsList($uin , 0);
			
			// 获取用户信息
			loadLib('User');
			$list_info = User::getBaseInfo($list);
			
			$smarty->assign('list_info' , $list_info);
		}
		
		$smarty->assign('info' , $info);
		
		return $smarty->fetch('app/factory/office_secretary.tpl.php');
	}
	
	/**
	 * 保安办公室
	 */
	function office_police() {
		$uin = sessionInfo('uin');
		$time_now = isset($_SERVER['REQUEST_TIME']) ? $_SERVER['REQUEST_TIME'] : time();

		$smarty = loadSmarty();
		loadLib('App_factory');
		
		$info = App_factory::updateState($uin , null , true);

		// 随机事件
		if($event_page = $this->_event_guide('office_police' , $info)) {
			return $event_page;
		}
		
		// 计算还剩余的时间
		if(count($info['police']) > 0) {
			$list = App_factory::getFriendsList($uin , 0);
			
			// 获取用户信息
			loadLib('User');
			$list_info = User::getBaseInfo($list);
			
			$smarty->assign('list_info' , $list_info);
		}
		
		$smarty->assign('info' , $info);
		
		return $smarty->fetch('app/factory/office_police.tpl.php');
	}
	
	/**
	 * 开始生产
	 */
	function start_lines() {
		$start = isset($_POST['start']) ? intval($_POST['start']) : 0;
		
		if($start != 1) {
			return View::error('非法操作');
		}
		
		$uin = sessionInfo('uin');
		
		loadLib('App_factory');
		
		$info = App_factory::updateState($uin , null , true);
		
		// 判断当前状态
		if($info['lines_info']['state'] != 0) {
			if($info['lines_info']['state'] == 1) {
				return View::error('你当前的生产线正在生产中');
			} else {
				return View::error('你必须先收钱，才能继续生产');
			}
		}
		
		$code = App_factory::startLines($uin , $info);
		if($code !== 0) {
			return View::error('系统繁忙，请稍后再试' , $code);
		}
		
		header('Location: ' . SITEURL . '/app.php?m=factory&a=office_boss&sid=' . sessionInfo('skey'));
	}
	
	
	/**
	 * 结束生产，收钱
	 */
	function end_lines() {
		$end = isset($_POST['end']) ? intval($_POST['end']) : 0;
		
		if($end != 1) {
			return View::error('非法操作');
		}
		
		$uin = sessionInfo('uin');
		
		loadLib('App_factory');
		
		$info = App_factory::updateState($uin , null , true);
		
		// 判断当前状态
		if($info['lines_info']['state'] != 2) {
			return View::error('你当前生产线还没结束，不能收钱');
		}
		
		$earned = $info['lines_info']['earned'];

		loadLib('Currency');
		$code = Currency::update('app_factory' , $uin , $earned);
		if($code !== 0) {
			return View::error('系统繁忙，请稍后再试' , $code);
		}
		
		$code = App_factory::endLines($uin);
		if($code !== 0) {
			return View::error('系统繁忙，请稍后再试' , $code);
		}
		
		header('Location: ' . SITEURL . '/app.php?m=factory&a=office_boss&sid=' . sessionInfo('skey'));
	}
	
	
	/**
	 * 人事部
	 */
	function dept_hr() {
		$uin = sessionInfo('uin');
		$time_now = isset($_SERVER['REQUEST_TIME']) ? $_SERVER['REQUEST_TIME'] : time();

		$smarty = loadSmarty();
		loadLib('App_factory');
		
		$info = App_factory::updateState($uin , null , true);

		// 随机事件
		if($event_page = $this->_event_guide('dept_hr' , $info)) {
			return $event_page;
		}
		
		// 计算还剩余的时间
		if(count($info['secretary']) > 0) {
			$secretary_diff_time = $info['secretary_timer'] - $time_now;
			$secretary_diff_time_correct = $secretary_diff_time + (16 * 3600);		// 因为我们时区是8
			$secretary_diff_time_array = explode(':' , date('j:G:i:s' , $secretary_diff_time_correct));
			$smarty->assign('secretary_diff_time' , $secretary_diff_time_array);
		}
		
		if(count($info['police']) > 0) {
			$police_diff_time = $info['police_timer'] - $time_now;
			$police_diff_time_correct = $police_diff_time + (16 * 3600);		// 因为我们时区是8
			$police_diff_time_array = explode(':' , date('j:G:i:s' , $police_diff_time_correct));
			$smarty->assign('police_diff_time' , $police_diff_time_array);
		}
		
		
		$smarty->assign('info' , $info);
		
		return $smarty->fetch('app/factory/dept_hr.tpl.php');
	}
	
	
	/**
	 * 建设部
	 */
	function dept_construction() {
		$uin = sessionInfo('uin');
		$time_now = isset($_SERVER['REQUEST_TIME']) ? $_SERVER['REQUEST_TIME'] : time();

		$smarty = loadSmarty();
		loadLib('App_factory');
		
		$info = App_factory::updateState($uin , null , true);

		// 随机事件
		if($event_page = $this->_event_guide('dept_construction' , $info)) {
			return $event_page;
		}
		
		loadLib('Currency');
		$currency = Currency::get('app_factory' , $uin);
		
		// 判断是否可以扩建生产线
		$could_addlines = true;
		
		$level_info = App_factory::getLevelInfo($info['lines']);
		if(date('Y-m-d' , time()) == date('Y-m-d' , $info['lines_add_timer'])) {
			// 判断一天内是否扩建过一次了 (这里做的判断规则是，是否是Y-m-d相同，也就是说，判断是否是同一天)
			$could_addlines = 'time';
		} else if(!empty($level_info['upgrade_fee'])) {
			// 已经到到了升级阶段，不能再扩建生产线
			$could_addlines = 'upgrade';
		} else if($currency < $level_info['addlines_fee']) {
			// 没有钱扩建生产线
			$could_addlines = 'fee';
		}
		
		$smarty->assign('info' , $info);
		$smarty->assign('currency' , $currency);
		$smarty->assign('could_addlines' , $could_addlines);
		$smarty->assign('level_info' , $level_info);
		
		return $smarty->fetch('app/factory/dept_construction.tpl.php');
	}
	
	/**
	 * 扩建一条生产线
	 */
	function addlines() {
		$uin = sessionInfo('uin');
		
		loadLib('App_factory');
		
		$info = App_factory::updateState($uin , null , true);
		
		loadLib('Currency');
		$currency = Currency::get('app_factory' , $uin);
		
		// 判断是否可以扩建生产线
		$could_addlines = true;
		
		$level_info = App_factory::getLevelInfo($info['lines']);
		if(date('Y-m-d' , time()) == date('Y-m-d' , $info['lines_add_timer'])) {
			// 判断一天内是否扩建过一次了 (这里做的判断规则是，是否是Y-m-d相同，也就是说，判断是否是同一天)
			return View::error('今天你已经扩建过生产线了');
		} else if(!empty($level_info['upgrade_fee'])) {
			// 已经到到了升级阶段，不能再扩建生产线
			return View::error('你必须升级后才能继续扩建生产线');
		} else if($currency < $level_info['addlines_fee']) {
			// 没有钱扩建生产线
			return View::error('你没有足够的银币来升级，升级需要' . $level_info['addlines_fee'] . '银币');
		}
		
		// 写数据库
		$code = App_factory::addLines($uin , $info['lines']);
		if($code !== 0) {
			return View::error('系统错误，请稍后再试' , $code);
		}
		
		// 扣钱
		Currency::update('app_factory' , $uin , 0 - $level_info['addlines_fee']);
		
		return View::success('扩建成功');
	}
	
	
	/**
	 * 招秘书
	 */
	function hire_secretary() {
		$uin = sessionInfo('uin');
		
		loadLib('App_factory');
		
		$info = App_factory::updateState($uin , null , true);
		
		if(!empty($info['secretary'])) {
			return View::error('你已经有秘书拉，不用再招了');
		}
		
		loadLib('Currency');
		$currency = Currency::get('app_factory' , $uin);
		
		// 花费
		$fee = 1000;
		
		if($currency < $fee) {
			return View::error('没钱了，招一个秘书需要' . $fee . '银币，你只有' . $currency . '银币');
		}
		
		// 写数据库
		$code = App_factory::hireSecretary($uin , 0 , $info['secretary']);
		if($code !== 0) {
			return View::error('系统错误，请稍后再试' , $code);
		}
		
		// 扣钱
		Currency::update('app_factory' , $uin , 0 - $fee);
		
		return View::success('招到一个秘书');
	}
	
	/**
	 * 招保安
	 */
	function hire_police() {
		$uin = sessionInfo('uin');
		
		loadLib('App_factory');
		
		$info = App_factory::updateState($uin , null , true);
		
		if(!empty($info['police'])) {
			return View::error('你已经有保安拉，不用再招了');
		}
		
		loadLib('Currency');
		$currency = Currency::get('app_factory' , $uin);
		
		// 花费
		$fee = 1000;
		
		if($currency < $fee) {
			return View::error('没钱了，招一个保安需要' . $fee . '银币，你只有' . $currency . '银币');
		}
		
		// 写数据库
		$code = App_factory::hirePolice($uin , 0 , $info['police']);
		if($code !== 0) {
			return View::error('系统错误，请稍后再试' , $code);
		}
		
		// 扣钱
		Currency::update('app_factory' , $uin , 0 - $fee);
		
		return View::success('招到一个保安');
	}
	
	
	/**
	 * 查看别人的工厂
	 */
	function guest() {
		$uin = isset($_GET['uin']) ? intval($_GET['uin']) : null;
		$type = isset($_GET['type']) ? trim($_GET['type']) : null;
		
		if(empty($uin)) {
			return View::error('参数错误');
		}
		
		$login_uin = sessionInfo('uin');
		if($login_uin == $uin) {
			return $this->index();
		}
		
		loadLib('App_factory');
		
		$friend_list = App_factory::getFriendsList($login_uin , 1);
		
		$smarty = loadSmarty();
		
		// 获取用户信息
		loadLib('User');
		$user_info = User::getBaseInfo($uin);
		if(empty($user_info)) {
			return View::error('该用户还没有开通疯狂工厂');
		}
		
		$info = App_factory::getInfo($uin);
		if(empty($info)) {
			return View::error('该用户还没有开通疯狂工厂');
		}
		
		$info = App_factory::updateState($uin , $info , true);
		$earn = $info['lines_info']['earn'];
		$earned = $info['lines_info']['earned'];
		$thief = $info['lines_info']['thief'];
		
		$has_stolen = in_array($login_uin , $thief);
		$could_steal = ($earned / $earn) > 0.5 ? true : 'limit';		// 收入超过50%才可以偷
		
		// 判断秘书与保安是否今天还可以再偷
		if($could_steal === true) {
			$steal_time_info = App_factory::getStealTimes($login_uin);
			if($type == 'secretary' && $steal_time_info['secretary_times'] >= 10) {
				$could_steal = 'secretary';
			} elseif($type == 'police' && $steal_time_info['police_times'] >= 10) {
				$could_steal = 'police';
			}
		}
		
		$time_now = isset($_SERVER['REQUEST_TIME']) ? $_SERVER['REQUEST_TIME'] : time();
		
		if($info['lines_info']['state'] == 1) {
			// 正在生产状态 
			$diff_time = $info['lines_timer'] - $time_now;
			$diff_time_correct = $diff_time + (16 * 3600);		// 因为我们时区是8
			$diff_time_array = explode(':' , date('H:i:s' , $diff_time_correct));
			$smarty->assign('diff_time' , $diff_time_array);
		}
		
		
		$smarty->assign('uin' , $uin);
		$smarty->assign('user_info' , $user_info);
		$smarty->assign('info' , $info);
		$smarty->assign('has_stolen' , $has_stolen);
		$smarty->assign('could_steal' , $could_steal);
		$smarty->assign('earned' , $earned);
		$smarty->assign('lines_state' , $info['lines_info']['state']);
		$smarty->assign('type' , $type);
		$smarty->assign('friend_list' , $friend_list);
		
		return $smarty->fetch('app/factory/guest.tpl.php');
	}
	
	
	/**
	 * 偷钱
	 */
	function steal() {
		$uin = isset($_POST['uin']) ? intval($_POST['uin']) : null;
		$type = isset($_POST['type']) ? trim($_POST['type']) : null;
		
		if(empty($uin) || !in_array($type , array('secretary' , 'police'))) {
			return View::error('参数错误');
		}
		
		$login_uin = sessionInfo('uin');
		if($login_uin == $uin) {
			return View::error('参数错误');
		}
		
		loadLib('App_factory');
		$friend_list = App_factory::getFriendsList($login_uin , 1);
		if(!in_array($uin , $friend_list)) {
			return View::error('你不能偷该用户的银币');
		}
		
		// 获取用户信息
		loadLib('User');
		$user_info = User::getBaseInfo($uin);
		if(empty($user_info)) {
			return View::error('该用户还没有开通疯狂工厂');
		}
		
		
		
		$info = App_factory::getInfo($uin);
		if(empty($info)) {
			return View::error('该用户还没有开通疯狂工厂');
		}
		
		$info = App_factory::updateState($uin , $info , true);
		$earn = $info['lines_info']['earn'];
		$earned = $info['lines_info']['earned'];
		$thief = $info['lines_info']['thief'];
		
		$has_stolen = in_array($login_uin , $thief);
		$could_steal = ($earned / $earn) > 0.5 ? true : 'limit';		// 收入超过50%才可以偷
		
		if($has_stolen) {
			return View::error('你已经偷过了，这次不能再偷了');
		}

		if($could_steal === 'limit') {
			return View::error('他所剩无几了，行行好，不要再偷了');
		}
		
		// 判断秘书与保安是否今天还可以再偷
		if($could_steal === true) {
			$steal_time_info = App_factory::getStealTimes($login_uin);
			if($type == 'secretary' && $steal_time_info['secretary_times'] >= 10) {
				return View::error('秘书今天已经偷过10次了，不能再偷了');
			} elseif($type == 'police' && $steal_time_info['police_times'] >= 10) {
				return View::error('保安今天已经偷过10次了，不能再偷了');
			}
		}
		
		// 加今天偷的次数
		App_factory::updateStealTimes($login_uin , $type);
		
		// 判断对方是否有保安，有的话，只有50%的几率可以偷到
		if( count($info['police']) > 0) {
			$steal_success = rand(0,99);
			if($steal_success >= 50) {
				return View::error($user_info['name'] . '的保安抓到了你，偷钱失败');
			}
		}
		
		// 一次偷 5% - 20%
		$steal_percent = rand(5 , 20);
		$steal_money = ceil( $earn * ($steal_percent / 100) );
		
		// 加钱
		$code = App_factory::steal($login_uin , $uin , $steal_money , $info);
		if($code !== 0) {
			return View::error('系统繁忙，请稍后再试' , $code);
		}
		
		// 发系统消息
		loadLib('SysMsg');
		SysMsg::sendSystem($uin , array(
			'send_uin' => $login_uin,
			'money' => $steal_money,
		) , 2001);
		
		return View::success('成功偷到了' . $steal_money . '银币');
	}


	/**
	 * 事件详情
	 */
	function event_info() {
		$id = isset($_GET['event_id']) ? intval($_GET['event_id']) : null;

		if(empty($id)) {
			return View::error('参数错误');
		}

		$uin = sessionInfo('uin');

		$smarty = loadSmarty();
		loadLib('App_factory');

		
		$info = App_factory::updateState($uin , null , true);

		$time_now = isset($_SERVER['REQUEST_TIME']) ? $_SERVER['REQUEST_TIME'] : time();

		if($info['event_id'] == $id || $time_now - $info['event_timer'] <= 3600) {
			return View::error('系统繁忙，请稍后再试' , 1211);
		}

		loadLib('App_Factory_Event');
		$event_info = App_Factory_Event::getById($id);
		if(empty($event_info)) {
			return View::error('系统繁忙，请稍后再试' , 1212);
		}

		function eventFormat($str) {
			return App_Factory_Event::formatContent($str);
		}
		// $smarty->registerPlugin('modifier' , 'eventFormat' , 'App_Factory_Event::formatContent');
		$smarty->assign('event' , $event_info);
		return $smarty->fetch('app/factory/event_info.tpl.php');
	}

	/**
	 * 事件结果
	 */
	function event_result() {
		$id = isset($_POST['event_id']) ? intval($_POST['event_id']) : null;

		if(empty($id)) {
			return View::error('参数错误');
		}

		$uin = sessionInfo('uin');

		$smarty = loadSmarty();
		loadLib('App_factory');

		$info = App_factory::updateState($uin , null , true);

		$time_now = isset($_SERVER['REQUEST_TIME']) ? $_SERVER['REQUEST_TIME'] : time();

		if($info['event_id'] == $id || $time_now - $info['event_timer'] <= 3600) {
			return View::error('系统繁忙，请稍后再试' , 1211);
		}

		loadLib('App_Factory_Event');
		$event_info = App_Factory_Event::getById($id);
		if(empty($event_info)) {
			return View::error('系统繁忙，请稍后再试' , 1212);
		}

		// 计算结果的概率，给奖励
		$result_info = array();
		$rand = rand(1 , 100);
		$offset = 0;
		foreach($event_info['result'] as $result) {
			if($rand <= $result['probability'] + $offset) {
				// 中了，使用这个结果
				$result_info = $result;
				break;
			} else {
				$offset += $result['probability'];
			}
		}
		$event_info['result_info'] = $result_info;

		// 奖罚
		$code = App_Factory_Event::gain($uin , $result_info);
		if($code !== 0) {
			return View::error('系统繁忙，请稍后再试' , $code);
		}


		// 修改时间
		App_Factory_Event::updateTimer($uin , $id);

		function eventFormat($str) {
			return App_Factory_Event::formatContent($str);
		}
		// $smarty->registerPlugin('modifier' , 'eventFormat' , 'App_Factory_Event::formatContent');
		$smarty->assign('event' , $event_info);
		return $smarty->fetch('app/factory/event_result.tpl.php');
	}


	/**
	 * 取消事件
	 */
	function event_cancel() {
		$id = isset($_GET['event_id']) ? intval($_GET['event_id']) : null;
		$place = isset($_GET['place']) ? trim($_GET['place']) : null;

		loadLib('App_Factory_Event');
		$places = App_Factory_Event::getPlaceName();

		if(empty($id) || empty($place) || !array_key_exists($place , $places)) {
			return View::error('参数错误');
		}

		$uin = sessionInfo('uin');

		// 修改时间
		App_Factory_Event::updateTimer($uin , $id);

		header('Location: ' . SITEURL . '/app.php?m=factory&a=' . $place . '&sid=' . sessionInfo('skey') );
	}



	/**
	 * 获取随机事件
	 */
	function _event_guide($place , $info) {
		$time_now = isset($_SERVER['REQUEST_TIME']) ? $_SERVER['REQUEST_TIME'] : time();

		$smarty = loadSmarty();

		// 判断随机事件，1小时触发一次
		if($time_now - $info['event_timer'] > 3600) {
			loadLib('App_Factory_Event');
			if( ($event_info = App_Factory_Event::get($place) ) && $event_info['id'] != $info['event_id'] ) {
				function eventFormat($str) {
					return App_Factory_Event::formatContent($str);
				}
				// $smarty->registerPlugin('modifier' , 'eventFormat' , 'App_Factory_Event::formatContent');
				$smarty->assign('event' , $event_info);
				return $smarty->fetch('app/factory/event_guide.tpl.php');
			}
		}

		return false;
	}



	/**
	 * PK塔
	 */
	function pk() {
		$uin = sessionInfo('uin');

		$smarty = loadSmarty();
		loadLib('App_factory');

		$info = App_factory::getPkInfo($uin);

		// 判断今天是否活动过了（PK失败，或收过奖励了）
		$has_done = false;
		$today_ts = strtotime( date('Y-m-d') );
		if($info['timer'] >= $today_ts) {
			$has_done = true;
		}

		if(!$has_done) {
			// 获取用户可以领奖的数目
			$awards = App_factory::getPkAwards($info['level']);
			$smarty->assign('awards' , $awards);
		}

		$smarty->assign('info' , $info);
		$smarty->assign('has_done' , $has_done);
		
		return $smarty->fetch('app/factory/pk.tpl.php');
	}

	/**
	 * PK上一层
	 */
	function pk_nextlevel() {
		$uin = sessionInfo('uin');

		loadLib('App_factory');

		$info = App_factory::getPkInfo($uin);

		$time_now = time();

		// 判断今天是否活动过了（PK失败，或收过奖励了）
		$has_done = false;
		$today_ts = strtotime( date('Y-m-d' , $time_now) );
		if($info['timer'] >= $today_ts) {
			$has_done = true;
		}

		if($has_done) {
			return View::error('你今天已经挑战失败或领取过奖励了，请明天再来');
		}

		$pk_level = $info['level'] + 1;
		if($pk_level > 100) {
			return View::error('你已经站在了世界的巅峰了');
		}

		// 获取这一级别的所有人
		$Db = loadDB();
		$level_uins = $Db->getAll("SELECT `uin` FROM `app_factory_pk` WHERE `level` = {$pk_level}");
		if($level_uins === false) {
			return View::error('系统错误，请稍后再试');
		}

		// 判断该层人数是否没满，没满则可直接晋级
		if(count($level_uins) < App_factory::getPKMaxUin($pk_level)) {
			$code = App_factory::pk_toLevel($uin , $pk_level);
			if($code === 0) {
				return View::success('你跑到了第' . $pk_level . '层，发现人还没满，赶紧站稳了脚跟');
			} else {
				return View::error('系统错误，请稍后再试' , $code);
			}
		}

		// 人数满了，随机选出一个人PK
		$rand_index = rand(0 , count($level_uins) - 1);
		$to_uin = $level_uins[$rand_index]['uin'];
		loadLib('User');
		$to_uin_info = User::getBaseInfo($to_uin);


		// 开始PK
		$win = false;
		$code = App_factory::PK($uin , $to_uin , $win);
		if($code !== 0) {
			return View::error('系统错误，请稍后再试' , $code);
		}

		if($win === false) {
			// 输了，更新时间戳
			$Db->query("UPDATE `app_factory_pk` SET `timer` = {$time_now} WHERE `uin` = {$uin}");
			return View::success('挑战失败，你输给了' . $to_uin_info['name'] . '，还是留在了原地，没有冲上 ' . $pk_level . ' 层');
		}

		// 赢了
		$code = App_factory::pk_toLevel($uin , $pk_level);
		if($code !== 0) {
			return View::error('系统错误，请稍后再试' , $code);
		}

		$code = App_factory::pk_toLevel($to_uin , $pk_level - 1);
		if($code !== 0) {
			return View::error('系统错误，请稍后再试' , $code);
		}

		// 发送系统消息给输了的人
		loadLib('SysMsg');
		SysMsg::sendSystem($to_uin , array(
			'level' => $pk_level,
			'send_uin' => $uin,
		) , 2002);

		return View::success('挑战成功，你打败了' . $to_uin_info['name'] . '，成功冲上 ' . $pk_level . ' 层');
	}

	function pk_getawards() {
		$uin = sessionInfo('uin');

		loadLib('App_factory');

		$info = App_factory::getPkInfo($uin);

		$time_now = time();

		// 判断今天是否活动过了（PK失败，或收过奖励了）
		$has_done = false;
		$today_ts = strtotime( date('Y-m-d' , $time_now) );
		if($info['timer'] >= $today_ts) {
			$has_done = true;
		}

		if($has_done) {
			return View::error('你今天已经挑战失败或领取过奖励了，请明天再来');
		}

		$awards = App_factory::getPkAwards($info['level']);

		loadLib('Currency');
		$code = Currency::update('app_factory' , $uin , $awards['currency']);
		if($code !== 0) {
			return View::error('系统错误，请稍后再试' , $code);
		}

		// 获取这一级别的所有人
		$Db = loadDB();

		$Db->query("UPDATE `app_factory_pk` SET `timer` = {$time_now} WHERE `uin` = {$uin}");

		return View::success('领取奖励银币 ' . $awards['currency'] . ' 成功');
	}
}


# end of script
